package com.kkb.kkbportal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kkb.kkbcommon.service.RedisService;
import com.kkb.kkbportal.dao.UserLikeScoreMapper;
import com.kkb.kkbportal.domain.UserLikeScore;
import com.kkb.kkbportal.service.ScoreLikeCountService;
import com.kkb.kkbportal.service.UserLikeScoreService;
import com.kkb.kkbportal.service.util.RedisKeyEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserLikeScoreServiceImpl
 * @Description 用户对评论点赞
 * @Author syt
 * @Date 2021/8/20
 **/
@Service
public class UserLikeScoreServiceImpl extends ServiceImpl<UserLikeScoreMapper, UserLikeScore> implements UserLikeScoreService {

    @Autowired
    private ScoreLikeCountService scoreLikeCountService;
    @Autowired
    private RedisService redisService;


    /**
     * 点赞功能
     *
     * @param userId  点赞人id
     * @param scoreId 被点赞的评论id
     * @return 是否点赞了
     */
    @Override
    public boolean like(Long userId, Long scoreId) {
        // 1. 查询点赞人是否对该评论点过赞的记录，不存在，添加

        String userIdKey = RedisKeyEnums.USER_LIKE_SCORE.getRedisKey() + userId;
        String scoreIdKey = String.valueOf(scoreId);

        Boolean hHasKey = redisService.hHasKey(userIdKey, scoreIdKey);
        Boolean liked = null;

        if (!hHasKey) {
            // 添加
            redisService.hSet(userIdKey, scoreIdKey, true);
        } else {
            liked = (Boolean)redisService.hGet(userIdKey, scoreIdKey);
            if (liked) {
                // 若点赞，则取消点赞，点赞数-1
                redisService.hSet(userIdKey, scoreIdKey, false);
                scoreLikeCountService.countScoreLike(scoreId, -1);
            } else {
                // 若未点赞，则点赞，点赞数+1
                redisService.hSet(userIdKey, scoreIdKey, true);
                scoreLikeCountService.countScoreLike(scoreId, 1);
            }
        }

        liked = (Boolean) redisService.hGet(userIdKey, scoreIdKey);
        return liked;
    }
}
